﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DAL
{
    public partial class ExpenseLineDislocation : IGetValue
    {
        public decimal GetExpenseValue()
        {
            return Convert.ToDecimal(this.Distance)*Convert.ToDecimal(0.4);//ver aqui o 0.4
        }

        public static ExpenseLineDislocation Get(Guid id)
        {
            DataAccessDataContext dc = new DataAccessDataContext();
            IQueryable<ExpenseLineDislocation> q = from e in dc.ExpenseLineDislocations
                    where e.Id.Equals(id)
                    select e;
            int count = q.Count();
            if (count == 0)
                return null;
            ExpenseLineDislocation eld = q.First();
            return eld;
        }

        public void Save()
        {
            using (DataAccessDataContext dc = new DataAccessDataContext())
            {
                var q = from eld in dc.ExpenseLineDislocations
                        where eld.Id.Equals(this.Id)
                        select eld;
                int count = q.Count<ExpenseLineDislocation>();
                ExpenseLineDislocation exp = null;
                if (count == 1)
                    exp = q.First<ExpenseLineDislocation>();
                if (exp == null)
                {
                    var query = from e in dc.ExpenseLines
                                where e.Id.Equals(this.Id)
                                select e;
                    ExpenseLine expLine = query.Single<ExpenseLine>();
                    expLine.Value = this.GetExpenseValue();
                    dc.ExpenseLineDislocations.InsertOnSubmit(this);
                }
                else
                {
                    exp.Arrival = this.Arrival;
                    exp.Departure = this.Departure;
                    exp.Distance = this.Distance;
                    exp.ExpenseLine.Value = this.GetExpenseValue();
                }
                dc.SubmitChanges();
            }
        }
    }
}
